import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import { IOrganizationUnitsTreeComponentData, OrganizationUnitsTreeComponent } from '../shared/organization-unit-tree.component';
import { ProcessingDeliverySubCreateComponent } from '../ProcessingDeliveryCreate/ProcessingDeliverySubCreate/ProcessingDeliverySubCreate.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TaskService } from '../task/Task.service';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { ProfileServiceProxy, OutsourcingWorkFlowServiceProxy, TaskServiceProxy, WorkflowServiceProxy, ProcessingDeliveryDto, ProcessingDeliveryViewDto, ProcessingDeliveryInputDto, ProcessingDeliveryStepUserDto, SelectItemGroup, UserServiceProxy } from '@shared/service-proxies/service-proxies';
import { from } from 'rxjs';


@Component({
  selector: 'ProcessingDeliveryCreate',
  templateUrl: './ProcessingDeliveryCreate.component.html',
  styleUrls: ['./ProcessingDeliveryCreate.component.css']
})
export class ProcessingDeliveryCreateComponent extends AppComponentBase {
  @ViewChild('ProcessingDeliverySubCreate') ProcessingDeliverySubCreate: ProcessingDeliverySubCreateComponent;
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('teskdataTable') teskdataTable: Table;

  active = false;
  saving = false;
  filterText = '';
  selectedCar3: string;
  index = 0;

  stepusers: ProcessingDeliveryStepUserDto;
  users: SelectItemGroup[];

  detailsprimengTableHelper: PrimengTableHelper;
  _processingDeliveryViewDto: ProcessingDeliveryViewDto[];
  clonedOutsourcings: { [s: number]: ProcessingDeliveryViewDto; } = {};
  selectProcessingDeliveryViewDto: ProcessingDeliveryViewDto[];

  _processingDelivery: ProcessingDeliveryDto = new ProcessingDeliveryDto();
  constructor(injector: Injector,
    private _outSourcingworkflowServiceProxy: OutsourcingWorkFlowServiceProxy,
    private _taskServiceProxy: TaskServiceProxy,
    private _userService: UserServiceProxy,
    private _workflowService: WorkflowServiceProxy
  ) {
    super(injector);
    this.detailsprimengTableHelper = new PrimengTableHelper();
    this.stepusers = new ProcessingDeliveryStepUserDto();
  }
  // tslint:disable-next-line: use-life-cycle-interface
  ngOnInit(): void {

    // this.selectProcessingViewDto = new Array<ProcessingViewDto>();
    this._userService.getAllUserForDropDown().subscribe(resultdata => {
      console.log(resultdata);
      this.users = resultdata;
    });
  }
  show(): void {
    this.active = true;
    this.modal.show();
  }
  close(): void {
    this.active = false;
    this.modal.hide();
  }
  onShown(): void {

  }
  getTasks(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }
    this.primengTableHelper.showLoadingIndicator();
    this._outSourcingworkflowServiceProxy.getProcessingDeliveryByCode(
      this.filterText,
      //this.primengTableHelper.getSorting(this.dataTable),
      'Code',
      // this.primengTableHelper.getMaxResultCount(this.paginator, event),
      10,
      //this.primengTableHelper.getSkipCount(this.paginator, event),
      0
    )
      .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
      .subscribe(result => {
        console.log(result);
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
      });
  }

  //依据申请单获取任务
  SelectTask(record) {
    this._processingDelivery.productionUnit = record.applyUnit;
    this._processingDelivery.supplierUnit = record.supplierUnit;
    //this._processingDelivery.requisitionCode = record.requisitionCode;
    this._outSourcingworkflowServiceProxy.getProcessingDeliveryDtoByWorkflowId(record.workflowId).subscribe(dto => {
      console.log(dto)
      this._processingDeliveryViewDto = dto;
      this.detailsprimengTableHelper.totalRecordsCount = dto.length;
      this.detailsprimengTableHelper.records = dto;
      this.detailsprimengTableHelper.hideLoadingIndicator();

      _.forEach(dto, viewItem => {
        //viewItem.processingId = record.id;
        console.log(viewItem.taskForModelId);
        this._taskServiceProxy.getTaskForEdit(viewItem.taskForModelId)
          .subscribe(userResult => {
            viewItem.taskCode = userResult.displayName;
            viewItem.taskName = userResult.code;
            viewItem.picNo = userResult.picNo;
        });
        this._outSourcingworkflowServiceProxy.getProcessingDeliveryAmountForTaskId(viewItem.taskForModelId)
        .subscribe(result => {
          viewItem.deliveredAmount = result;
        });
      });
    });
    this.index = 1;
  }
  handleChange(e) {
    this.index = e.index;
    console.log(this.index);
  }

  onRowEditInit(dto: ProcessingDeliveryViewDto) {
    console.log(dto);
    this.clonedOutsourcings[dto.taskForModelId.toString()] = { ...dto };
  }
  //保存行编辑
  onRowEditSave(dto: ProcessingDeliveryViewDto) {
    console.log(dto);

    delete this.clonedOutsourcings[dto.taskForModelId.toString()];
    this.selectProcessingDeliveryViewDto = new Array();
    let _current = this.selectProcessingDeliveryViewDto.find((element) => (element.taskForModelId === dto.taskForModelId));
    if (_current === undefined) {
      dto.deliveryDate = dto.deliveryDate;
      dto.passedAmount = dto.passedAmount;
      dto.quantityAmount = dto.quantityAmount;
      dto.noPassedAmount = dto.noPassedAmount;
      dto.qualityControlCardNo = dto.qualityControlCardNo;
      dto.deliveryAmount = dto.passedAmount +  dto.quantityAmount + dto.noPassedAmount;
      const date1: any = dto.progressrequest; // the date you already commented/ posted
      const date2: any = dto.deliveryDate; // today

      let r = {}; // object for clarity
      let message: string;

      const diffInSeconds = (date2 - date1) / 1000;
      const days = Math.floor(diffInSeconds / 60 / 60 / 24);
      if (days > 0) { //逾期
        dto.overdueDay = days;
        dto.isOverdue = true;
      } else {
        dto.overdueDay = 0;
        dto.isOverdue = false;
      }
      this.selectProcessingDeliveryViewDto.push(dto);
    } else {
      _current.deliveryAmount = dto.deliveryAmount;
    }
  }
  //取消行编辑
  onRowEditCancel(dto: ProcessingDeliveryViewDto, index: number) {
    console.log(this.clonedOutsourcings[dto.taskForModelId.toString()]);
    this._processingDeliveryViewDto[index] = this.clonedOutsourcings[dto.taskForModelId.toString()];
    delete this._processingDeliveryViewDto[dto.taskForModelId];
  }

  save() {
    console.log(this._processingDelivery);
    console.log(this._processingDeliveryViewDto);
    let input = new ProcessingDeliveryInputDto();

    //判断审批用户是否设置
    if (!this.stepusers.qualityDepartmentManager) {
      this.notify.info('请选择质量处主管');
      this.saving = false;
      return;
    }
    if (!this.stepusers.workShopManager) {
      this.notify.info('请选择车间主管');
      this.saving = false;
      return;
    }
    if (!this.stepusers.workShopLeader) {
      this.notify.info('请选择车间领导');
      this.saving = false;
      return;
    }
    if (!this.stepusers.qualityDepartmentLeader) {
      this.notify.info('请选择质量管理处处长');
      this.saving = false;
      return;
    }

    input.stepUserDto = this.stepusers;
    input.processingDeliveryDto = this._processingDelivery;
    input.processingDeliveryViewDtos = this._processingDeliveryViewDto;
    this.saving = true;

    console.log(input);
    this._outSourcingworkflowServiceProxy.createOrUpdateProcessingDeliveryWorkFlow(input)
      .pipe(finalize(() => { this.saving = false; }))
      .subscribe(() => {
        this.close();
      });
  }
}
